<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Request;
use \jwt\JWT;

class User extends Home
{
    public function _initialize()
    {
        parent::_initialize();
        $this->checkToken();
    }

    public function checkToken($uid = '')
    {
        $header = Request::instance()->header();
        if (empty($header['authorization'])) {
            echo json_encode([
                'status' => 1002,
                'msg' => 'Token不存在,拒绝访问',
                'auth' => $header['authorization'],
                'header' => $header
            ]);
            exit;
        } else {
            $checkJwtToken = $this->verifyJwt($header['authorization']);
            if ($checkJwtToken['status'] == 1001) {
                if($uid) {
                    return $checkJwtToken['user_id'];
                } else {
                    return true;
                }
            }
        }
    }

    //校验jwt权限API
    protected function verifyJwt($jwt)
    {
        $key = md5('plain');
        // JWT::$leeway = 3;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            $msg = [];
            if (!empty($authInfo['user_id'])) {
                $msg = [
                    'user_id' => $authInfo['user_id'],
                    'status' => 1001,
                    'msg' => 'Token验证通过'
                ];
            } else {
                $msg = [
                    'status' => 1002,
                    'msg' => 'Token验证不通过,用户不存在'
                ];
            }
            return $msg;
        } catch (\jwt\SignatureInvalidException $e) {
            echo json_encode([
                'status' => 1002,
                'msg' => 'Token无效'
            ]);
            exit;
        } catch (\jwt\ExpiredException $e) {
            echo json_encode([
                'status' => 1003,
                'msg' => 'Token过期'
            ]);
            exit;
        } catch (Exception $e) {
            return $e;
        }
    }

    // 获取用户资料
    public function getuserinfo()
    {
        $rs = model('User');
        $user = $rs->get_user_info($this->checkToken(1));
        if ($user) {
            $list['userid'] = $user['user_id'];
            $list['nickname'] = $user['user_nickname'];
            $list['name'] = $user['user_name'];
            $list['avatar'] = zanpian_avatar_url($user);
            return json($list);
        } else {
            return json((object) array());
        }
    }

    // 添加评论
    public function addcm()
    {
        $param = input();
        $uid = $this->checkToken(1);
        if ($this->request->isPost()) {
            if (!$uid) {
                return json(['msg' => '请先登录', 'code' => -2]);
            }
            if ($GLOBALS['config']['user']['sys']['user_code'] == 1) {
                if (!captcha_check($param['validate'])) {
                    return json(['msg' => '验证码错误', 'code' => -1]);
                }
            }
            $rs = model('Cm');
            $data = array();
            $data['cm_content'] = (string) htmlspecialchars(strip_tags(input('post.comm_txt/s')));
            $data['cm_vid'] = input('id/d');
            $data['cm_uid'] = $uid;
            $data['cm_username'] = (string) $param['user_nickname'];
            $data['cm_sid'] = input('sid/d', 1);
            $data['cm_pid'] = input('post.comm_pid/d', 0);
            $data['cm_addtime'] = time();
            $data['checktime'] = 1;
            if (empty($data['cm_content'])) {
                return json(['msg' => '内容不能为空!', 'code' => -1]);
            }
            if ($rs->validate('cm')->save($data) !== false) {
                if ($GLOBALS['config']['user']['sys']['user_cm_score']) {
                    model('Score')->user_score($uid, 12, intval($GLOBALS['config']['user']['sys']['user_cm_score']));
                }
                $list['cookietime'] = intval($GLOBALS['config']['user']['sys']['user_cm_time']);
                $list['cookiename'] = md5('cm-' . bindec(decbin(ip2long(request()->ip()))) . '-' . intval($data['cm_vid']) . '-' . intval($data['cm_uid']));
                if ($GLOBALS['config']['user']['sys']['user_check'] == 1) {
                    return json(['data' => $list, 'msg' => '评论提交成功,我们会尽快审核你的回复！', 'code' => 1]);
                } else {
                    return json(['data' => $list, 'msg' => '评论提交成功', 'code' => 1]);
                }
            } else {
                return json(['msg' => '评论提交失败,' . $rs->getError(), 'code' => -1]);
            }
        }
    }
    // 添加回复
    public function addrecm()
    {
        $param = input();
        $uid = $this->checkToken(1);
        if ($this->request->isPost()) {
            if (!$uid) {
                return json(['msg' => "请先登录", 'code' => -2]);
            }
            if ($GLOBALS['config']['user']['sys']['user_code'] == 1) {
                if (!captcha_check($param['validate'])) {
                    return json(['msg' => '验证码错误', 'code' => -1]);
                }
            }
            $rs = model('Cm');
            $cm_pid = input('post.comm_pid/d', 0);
            $cm_id = input('post.comm_id/d', 0);
            $cm_tuid = input('post.comm_tuid/d', 0);
            $cm_vid = input('post.comm_vid/d', 0);
            $cm_sid = input('post.comm_sid/d', 1);
            $data = array();
            $data['cm_content'] = htmlspecialchars(strip_tags(input('post.recomm_txt/s', '')));
            $data['cm_vid'] = $cm_vid;
            $data['cm_uid'] = $uid;
            $data['cm_username'] = (string) $param['user_nickname'];
            $data['cm_sid'] = $cm_sid;
            $data['cm_pid'] = empty($cm_pid) ? $cm_id : $cm_pid;
            $data['cm_tid'] = !empty($cm_pid) ? $cm_id : 0;
            $data['cm_tuid'] = !empty($cm_tuid) ? $cm_tuid : 0;
            $data['cm_addtime'] = time();
            $data['checktime'] = 1;
            if (empty($data['cm_content'])) {
                return json(['msg' => "内容不能为空!", 'code' => -1]);
            }
            if ($rs->validate('cm')->save($data) !== false) {
                if ($GLOBALS['config']['user']['sys']['user_cm_score']) {
                    model('Score')->user_score($uid, 11, intval($GLOBALS['config']['user']['sys']['user_cm_score']));
                }
                $list['cookietime'] = intval($GLOBALS['config']['user']['sys']['user_cm_time']);
                $list['cookiename'] = md5('cm-' . bindec(decbin(ip2long(request()->ip()))) . '-' . intval($data['cm_vid']) . '-' . intval($data['cm_uid']));
                if ($GLOBALS['config']['use4r']['sys']['user_check'] == 1) {
                    return json(['data' => $list, 'msg' => '评论提交成功,我们会尽快审核你的回复！', 'code' => 1]);
                } else {
                    return json(['data' => $list, 'msg' => '评论提交成功', 'code' => 1]);
                }
            } else {
                return json(['msg' => '评论提交失败,' . $rs->getError(), 'code' => -1]);
            }
        }
    }

    /**
     * 查询是否收藏订阅
     */
    public function favoriteAndRemind()
    {
        $param = zanpiancms_param_url();
        $uid = $this->checkToken(1);
        $model = $GLOBALS['config']['model'][$param['sid']];
        $start = array();
        if (!empty($param['id']) && !empty($param['sid']) && !empty($model)) {
            //是否收藏
            if ($uid && $param['sid'] == 1) {
                $favorite = db('favorite')->where(array('favorite_vid' => $param['id'], 'favorite_uid' => $uid))->value('favorite_id');
                if ($favorite) {
                    $start['loveid'] = $param['id'];
                }
                $remin = db('remind')->where(array('remind_vid' => $param['id'], 'remind_uid' => $uid))->value('remind_id');
                if ($remin) {
                    $start['remindid'] = $param['id'];
                }
            }
            return json(['data' => $start]);
        } else {
            return json(['data' => $start]);
        }
    }

    /**
     * 订阅收藏
     */
    public function mark()
    {
        $param = zanpiancms_param_url();
        $uid = $this->checkToken(1);
        if (empty($uid)) {
            return json(['msg' => '请先登录', 'code' => -1]);
        }
        if (!empty($param['id']) && !empty($param['cid']) && !empty($param['type'])) {
            if ($param['type'] == 'love') {
                $rs = model('favorite');
                $where = [];
                $where['favorite_vid'] = $param['id'];
                $where['favorite_uid'] = $uid;
                $favorite = db('favorite')->where($where)->value('favorite_id');
                if (!empty($favorite)) {
                    if ($rs->where($where)->delete() !== false) {
                        return json(array('msg' => '取消收藏成功', 'code' => 1));
                    } else {
                        return json(array('msg' => $rs->getError(), 'code' => -1));
                    }
                } else {
                    $data['favorite_vid'] = $param['id'];
                    $data['favorite_uid'] = $uid;
                    $data['favorite_cid'] = $param['cid'];
                    $data['favorite_addtime'] = time();
                    if ($rs->save($data) !== false) {
                        return json(array('msg' => "收藏成功", 'code' => 1));
                    } else {
                        return json(array('msg' => $rs->getError(), 'code' => -1));
                    }
                }
            } else {
                $rs = model('remind');
                $where = [];
                $where['remind_vid'] = $param['id'];
                $where['remind_uid'] = $uid;
                $remind = db('remind')->where($where)->value('remind_id');
                if (!empty($remind)) {
                    if ($rs->where($where)->delete() !== false) {
                        return json(array('msg' => '取消订阅成功', 'code' => 1));
                    } else {
                        return json(array('msg' => $rs->getError(), 'code' => -1));
                    }
                } else {
                    $vod_addtime = db('vod')->where('vod_id')->value('vod_addtime');
                    $data['remind_vid'] = $param['id'];
                    $data['remind_uid'] = $uid;
                    $data['remind_cid'] = $param['cid'];
                    $data['remind_addtime'] = time();
                    $data['remind_uptime'] = $vod_addtime;
                    if ($rs->save($data) !== false) {
                        return json(array('msg' => "订阅成功", 'code' => 1));
                    } else {
                        return json(array('msg' => $rs->getError(), 'code' => -1));
                    }
                }
            }
        } else {
            return json(['msg' => '参数错误', 'code' => '-1']);
        }
    }

    /**
     * 获取观看记录 需要登录
     */

    public function playlog()
    {
        $uid = $this->checkToken(1);
        if ($uid) {
            $where = [];
            $where['uid'] = $uid;
            $rs = model('Playlog');
            $list = $rs->listData($where); //查询所有结果集
            if ($list) {
                foreach ($list as $key => $value) {
                    $data[$key]['id'] = $value['log_id'];
                    $data[$key]['title'] = $value['vod_name'];
                    $data[$key]['name'] = $value['log_urlname'];
                    $data[$key]['vid'] = $value['log_vid'];
                    $data[$key]['pid'] = $value['log_pid'];
                    if ($value['log_pid'] < $value['log_maxnum']) {
                        $data[$key]['next'] = $value['log_pid'] + 1;
                    }
                }
            }
            $result = array('data' => $data, 'total' => count($list), 'info' => 'ok', 'status' => 1);
        } else {
            $result = array('data' => [], 'info' => 'error', 'status' => 0);
        }
        return json($result);
    }
    /**
     * 添加观看记录 需要登录
     */
    public function addplaylog()
    {
        $uid = $this->checkToken(1);
        if ($uid) {
            $data['log_vid'] = input('id/d');
            $data['log_sid'] = input('sid/d');
            $data['log_pid'] = input('pid/d');
            $data['log_urlname'] = input('name/s');
            $data['log_maxnum'] = input('max/d');
            $data['log_uid'] = $uid;
            model('playlog')->addajax($data);
            return json(array("code" => 1));
        } else {
            return json(array("code" => -1));
        }
    }
    /**
     * 清空观看记录 需登录
     */
    public function clearplaylog()
    {
        $uid = $this->checkToken(1);
        if ($uid) {
            db('playlog')->where('log_uid', $uid)->delete();
        }
        return ['msg' => '清空成功', 'code' => 1];
    }
    /**
     * 删除观看记录 需登录
     */
    public function delplaylog()
    {
        $uid = $this->checkToken(1);
        if ($uid) {
            $where['log_id'] = input('id/d');
            $where['log_uid'] = $uid;
            return db('playlog')->where($where)->delete();
        }
    }

    // 评论顶踩
    public function cmdigg()
    {
        $param = zanpiancms_param_url();
        if (!empty($param['id']) && !empty($param['type'])) {
            if (in_array($param['type'], array('up', 'down'))) {
                db('cm')->where('cm_id', $param['id'])->setInc('cm_' . $param['type']);
                $data['cookietime'] = intval($GLOBALS['config']['user']['sys']['user_digg_time']);
                $data['cookiename'] = md5('cm-' . ip2long(request()->ip()) . '-' . intval($param['id']));
                return json(['data' => $data, 'msg' => '点评成功', 'code' => 1]);
            }
            return json(['msg' => '参数错误', 'code' => -1]);
        } else {
            return json(['msg' => '参数错误', 'code' => -1]);
        }
    }
}
